<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .box1{width:100px;height:100px;position: absolute;left:0;top:0;background: red;}
    
  </style>
</head>
<body>

  <div class="box1"></div>
  
</body>
<script>

  function Drag(ele){
    this.ele = ele;
    // 每次启动拖拽，都先读取本地存储，查看是否有之前的坐标
    this.getLocal();

    this.addEvent();
  }
  Drag.prototype.getLocal = function(){
    const l = localStorage.getItem("left") || 0;
    const t = localStorage.getItem("top") || 0;
    
    this.ele.style.left = l + "px";
    this.ele.style.top = t + "px";
  }
  Drag.prototype.addEvent = function(){
    const that = this;
    this.ele.onmousedown = function(eve){
      that.downE = eve || window.event;
      document.onmousemove = function(eve){
        that.moveE = eve || window.event;
        that.move();
      }
      document.onmouseup = function(){
        that.up();
      }
    }
  }
  Drag.prototype.move = function(){
    let l = this.moveE.pageX - this.downE.offsetX;
    let t = this.moveE.pageY - this.downE.offsetY;

    this.ele.style.left = l + "px";
    this.ele.style.top = t + "px";
  }
  Drag.prototype.up = function(){
    document.onmousemove = null;
    document.onmouseup = null;
    // 鼠标抬起，记录最后的坐标
    this.setLocal()
  }
  Drag.prototype.setLocal = function(){
    localStorage.setItem("left", this.ele.offsetLeft);
    localStorage.setItem("top", this.ele.offsetTop);
  }


  new Drag( document.querySelector(".box1") );

  
  
</script>
</html>